package services.kingdee

import play.api.libs.json.{JsValue, Json}
import play.api.libs.ws.WSClient
import play.api.{Configuration, Logging}

import scala.concurrent.duration.DurationInt
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


trait KingdeePostTrait extends Logging {
  protected var kdAppConfig: KingdeeConfig // test

  protected val ws: WSClient

  protected def post(api_url: String, data: JsValue, kddc: KingdeeConfig = kdAppConfig) = {
    if (kddc.serverUrl.isEmpty) {
      Future("{\"Result\":{\"ResponseStatus\":{\"IsSuccess\":false}}}")
    } else {
      logger.debug(s"kddc=$kddc")
      val serverUrl = kddc.serverUrl + (if (kddc.serverUrl.endsWith("/")) "" else "/") + api_url
      val headers = KingdeeAuthService.signature(serverUrl, System.currentTimeMillis().toString, kddc)
      ws.url(serverUrl).withRequestTimeout(120.second)
        .addHttpHeaders(
          ("X-Api-ClientID", headers.cliend_id),
          ("X-Api-Auth-Version", headers.version),
          ("X-Api-Auth-Version", headers.version),
          ("X-Api-Auth-Version", headers.version),
          ("x-api-timestamp", headers.timestamp),
          ("x-api-nonce", headers.nonce),
          ("x-api-signheaders", headers.api_signheaders),
          ("X-Api-Signature", headers.Api_Signature),
          ("X-Kd-Appkey", kddc.appId),
          ("X-Kd-Appdata", headers.Kd_Appdata),
          ("X-Kd-Signature", headers.Kd_Signature),
          ("Accept-Charset", headers.Accept_Charset),
          ("User-Agent", headers.User_Agent),
          ("Content-Type", headers.Content_Type)
        )
        .post(data)
        .map(r => {
          //println(r.status);
          r.body
        })
    }
  }

  def loginResult(result: String) = {
    val s = "response_error:Code(-2147467259);"
    if (result.startsWith(s))
      result.substring(33)
    else result
  }

  def getDataCenters(kddc: KingdeeConfig = kdAppConfig) = {
    val service_url = "Kingdee.BOS.ServiceFacade.ServicesStub.Account.AccountService.GetDataCenterList.common.kdsvc"
    val serverUrl = if (kddc.serverUrl.endsWith("/")) kddc.serverUrl + service_url else kddc.serverUrl + "/" + service_url
    ws.url(serverUrl).post(Json.obj()).map(r => r.body)
  }

  /**
   * 保存
   *
   * @param formid
   * @param data Json对象或字符串
   * @return
   */
  def save(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
    // {"formid": "BD_Empinfo","data": {"InterationFlags":"STK_InvCheckResult","Model":{"FName":"张三","FStaffNumber":"EM0001","FCreateOrgId":"100","FUseOrgId":"100"}}}
  )

  def save(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
    // {"parameters": ["BD_Empinfo","{\"InterationFlags\":\"STK_InvCheckResult\",\"Model\":{\"FName\":\"张三\",\"FStaffNumber\":\"EM0001\",\"FCreateOrgId\":\"100\",\"FUseOrgId\":\"100\"}}"]}
  )

  def batchSave(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def batchSave(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  /**
   * 审核
   *
   * @param formid
   * @param data Json对象或字符串
   * @return
   */
  def audit(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
    // {"formid": "PRD_MO", "data": {"Numbers": ["MO20122090410"]}}
  )

  def audit(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
    //  {"parameters":["PRD_MO","{\"Numbers\":[\"MO20122090410\"]}"]}
  )

  /**
   * 删除
   *
   * @param formid
   * @param data Json对象或字符串
   * @return
   */
  def delete(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
    // {"formid": "PRD_MO", "data": {"Numbers": ["MO20122090410"]}}
  )

  def delete(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
    //  {"parameters":["PRD_MO","{\"Numbers\":[\"MO20122090410\"]}"]}
  )

  /**
   * 反审核
   *
   * @param formid
   * @param data Json对象或字符串
   * @return
   */
  def unAudit(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
    // {"formid": "PRD_MO", "data": {"Numbers": ["MO20122090410"]}}
  )

  def unAudit(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
    //  {"parameters":["PRD_MO","{\"Numbers\":[\"MO20122090410\"]}"]}
  )

  /**
   * 提交
   *
   * @param formid
   * @param data Json对象或字符串
   * @return
   */
  def submit(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
    // {"formid": "PRD_MO", "data": {"Numbers": ["MO20122090410"]}}
  )

  def submit(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
    //  {"parameters":["PRD_MO","{\"Numbers\":[\"MO20122090410\"]}"]}
  )

  /**
   * 查看单据
   *
   * @param formid
   * @param data Json对象或字符串
   * @return
   */
  def view(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
    // {"formid": "PRD_MO", "data": {"Numbers": ["MO20122090410"]}}
  )

  def view(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
    //  {"parameters":["PRD_MO","{\"Numbers\":[\"MO20122090410\"]}"]}
  )

  /**
   * 单据查询
   *
   * @param data Json对象或字符串
   * @return
   */
  def executeBillQuery(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
    Json.obj("data" -> data)
  )

  def executeBillQuery(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
    Json.obj("parameters" -> Json.arr(data))
  )

  /**
   * 生产执行
   *
   * @param formid
   * @param opNumber 完工："ToFinish"
   * @param data     Json对象或字符串
   * @return
   */
  def excuteOperation(formid: String, opNumber: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation.common.kdsvc",
    Json.obj("formid" -> formid, "opNumber" -> opNumber, "data" -> data)
    // {"formid": "PRD_MO", "opNumber": "ToFinish", "data": {"Numbers": ["MO20122090410"]}}
  )

  def excuteOperation(formid: String, opNumber: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, opNumber, data))
    // {"parameters":["PRD_MO","ToFinish","{\"Numbers\":[\"MO20122090410\"]}"]}
  )

  def draft(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Draft.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def draft(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Draft.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  def allocate(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Allocate.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def allocate(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Allocate.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  def flexSave(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.FlexSave.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def flexSave(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.FlexSave.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  def sendMsg(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.SendMsg.common.kdsvc",
    Json.obj("data" -> data)
  )

  def sendMsg(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.SendMsg.common.kdsvc",
    Json.obj("parameters" -> Json.arr(data))
  )

  def push(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def push(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  def groupSave(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupSave.common.kdsvc",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def groupSave(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupSave.common.kdsvc",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  def disassembly(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Disassembly",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def disassembly(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Disassembly",
    Json.obj("parameters" -> Json.arr(formid, data))
  )


  def queryBusinessInfo(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryBusinessInfo",
    Json.obj("data" -> data)
  )

  def queryBusinessInfo(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryBusinessInfo",
    Json.obj("parameters" -> Json.arr(data))
  )

  def queryGroupInfo(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryGroupInfo",
    Json.obj("data" -> data)
  )

  def queryGroupInfo(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryGroupInfo",
    Json.obj("parameters" -> Json.arr(data))
  )

  def workflowAudit(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.WorkflowAudit",
    Json.obj("data" -> data)
  )

  def workflowAudit(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.WorkflowAudit",
    Json.obj("parameters" -> Json.arr(data))
  )

  def groupDelete(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupDelete",
    Json.obj("data" -> data)
  )

  def groupDelete(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupDelete",
    Json.obj("parameters" -> Json.arr(data))
  )

  def cancelAllocate(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.CancelAllocate",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def cancelAllocate(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.CancelAllocate",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  def switchOrg(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.SwitchOrg",
    Json.obj("data" -> data)
  )

  def switchOrg(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.SwitchOrg",
    Json.obj("parameters" -> Json.arr(data))
  )

  def cancelAssign(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.CancelAssign",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def cancelAssign(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.CancelAssign",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  def getSysReportData(formid: String, data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GetSysReportData",
    Json.obj("formid" -> formid, "data" -> data)
  )

  def getSysReportData(formid: String, data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GetSysReportData",
    Json.obj("parameters" -> Json.arr(formid, data))
  )

  def attachmentUpload(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.AttachmentUpload",
    Json.obj("data" -> data)
  )

  def attachmentUpload(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.AttachmentUpload",
    Json.obj("parameters" -> Json.arr(data))
  )

  def attachmentDownLoad(data: JsValue) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.AttachmentDownLoad",
    Json.obj("data" -> data)
  )

  def attachmentDownLoad(data: String) = this.post(
    "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.AttachmentDownLoad",
    Json.obj("parameters" -> Json.arr(data))
  )
}

